package com.iceland.server.server.cmd;

import com.iceland.common.message.CmdMessage;
import com.iceland.common.rpc.RpcMessageManager;
import com.iceland.common.thread.MessageEventExcutor;
import com.iceland.common.strategy.CmdStrategyFactory;
import com.iceland.common.util.AttributeKeyUtils;
import com.iceland.common.util.ChannelContext;
import com.iceland.server.server.proxy.ProxyServer;
import com.iceland.server.server.proxy.ProxyServerManager;
import com.iceland.server.util.ServerChannelContext;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MarkerFactory;

@Slf4j
public class CmdMessageHandler extends ChannelInboundHandlerAdapter {

    public CmdMessageHandler(){

    }


    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

        log.debug(MarkerFactory.getMarker(this.getClass().getTypeName()),"CMD客户端{}连接CMD服务器{}",ctx.channel().remoteAddress(),ctx.channel().localAddress());
    }


    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        CmdMessage m=(CmdMessage)msg;

        int type = m.getType();
        CmdStrategyFactory.getStrategy(type).doStrategy(ctx,m);


//        ctx.fireChannelRead(msg);
    }

    //断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.debug(MarkerFactory.getMarker(this.getClass().getTypeName()),"通道关闭，CMD客户端:{},CMD服务端：{}",channel.remoteAddress(),channel.localAddress());
        ChannelContext channelContext = AttributeKeyUtils.getChannelContext(channel);
        if(channelContext!=null ){
            RpcMessageManager rpcMessageManager = channelContext.getRpcMessageManager();
            if(rpcMessageManager!=null){
                Channel cmdChannel = rpcMessageManager.getChannel();
                if(cmdChannel!=null && cmdChannel==channel){

                    ServerChannelContext serverChannelContext=(ServerChannelContext)channelContext;
                    ProxyServer proxyServer = serverChannelContext.getProxyServer();
                    ProxyServerManager proxyServerManager = ProxyServerManager.getSingleInstance();
                    log.info(MarkerFactory.getMarker(this.getClass().getTypeName()),"客户端cmd通道断开，关闭对应代理服务器，释放代理端口{}",proxyServer.getPort());
                    proxyServerManager.closeServer(proxyServer.getPort());
                }
            }

        }

        if(channelContext!=null && channelContext.getBindChannel()!=null){
            channelContext.getBindChannel().close();
        }
        ctx.fireChannelInactive();
    }

}
